//
//  PXBaoViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-3-9.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "PXBaoViewController.h"
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import <QuartzCore/QuartzCore.h>
#import "MainTabBarController.h"
#import "LoginViewController.h"
#import "BaoSusViewController.h"
@interface PXBaoViewController ()

@end

@implementation PXBaoViewController
@synthesize m_BaoIDs;
- (id)init
{
    if (self = [super init]) {
        // Custom initialization
    }
    return self;
}

-(void) dealloc
{
    [_NameField release];
    [_PhoneField release];
    [_AddressField release];
    [_InputTableView release];
    [_NavBtt release];
    [m_BaoIDs release];
    [m_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
//    UILabel* tNavTitleLab = (UILabel*)[self.navigationController.navigationBar viewWithTag:144];
//    [tNavTitleLab setText:@"培训机构"];
    m_titleBttBarItem = [[MainTabBarController setTitle:@"培训机构"] retain];
    
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    
    _InputTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-44) style:UITableViewStyleGrouped];
    _InputTableView.delegate = self;
    _InputTableView.dataSource = self;
    [_InputTableView setBackgroundView:nil];
    [_InputTableView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_InputTableView];
    
    
    UIView* tBottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    [tBottomView setBackgroundColor:[UIColor clearColor]];
    UIButton* tApplyBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    tApplyBtt.frame =CGRectMake(10, 5, 300, 40);
    [tApplyBtt setImage:[UIImage imageNamed:@"button_yellow_l.png"] forState:UIControlStateNormal];
    [tBottomView addSubview:tApplyBtt];
    [tApplyBtt addTarget:self action:@selector(baoMingRequest) forControlEvents:UIControlEventTouchUpInside];
    UILabel* tBttlab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 300, 20)];
    [tBttlab setBackgroundColor:[UIColor clearColor]];
    [tBttlab setTextColor:[UIColor whiteColor]];
    [tBttlab setText:@"报名"];
    tBttlab.textAlignment =UITextAlignmentCenter;
    [tBttlab setFont:[UIFont boldSystemFontOfSize:17]];
    [tApplyBtt addSubview:tBttlab];
    [tBttlab release];
    _InputTableView.tableFooterView = tBottomView;
    [tBottomView release];
    
    
    _NameField = [[UITextField alloc] initWithFrame:CGRectMake(64, 10, 220, 20)];
    _PhoneField = [[UITextField alloc] initWithFrame:CGRectMake(64, 10, 220, 20)];
    _AddressField = [[UITextField alloc] initWithFrame:CGRectMake(64, 10, 220, 20)];
    
    _NameField.delegate = self;
    _PhoneField.delegate = self;
    _AddressField.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
    [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
    [m_titleBttBarItem removeFromSuperview];
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void) baoMingRequest
{
    [self requestListData];
}

#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* tNameCell  =@"inputcell";
    int tRow = indexPath.row;
    
    UITableViewCell* tCell = [tableView dequeueReusableCellWithIdentifier:tNameCell];
    if (tCell == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tNameCell] autorelease];
        UILabel* tTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(62, 10, 240,20)];
        [tTitleLab setBackgroundColor:[UIColor clearColor]];
        [tTitleLab setFont:[UIFont systemFontOfSize:15]];
        tTitleLab.tag =50;
        [tCell addSubview:tTitleLab];
        [tTitleLab release];
    }
    UILabel* tTitleLab = (UILabel*)[tCell viewWithTag:50];
    tCell.selectionStyle = UITableViewCellSelectionStyleNone;
    tTitleLab.frame =CGRectMake(18, 10, 240,20);
    if (tRow == 0) {
        tTitleLab.text =@"姓名";
        [tCell addSubview:_NameField];
    }else if (tRow == 1) {
        tTitleLab.text =@"手机";
        [tCell addSubview:_PhoneField];
    }else if (tRow == 2) {
        tTitleLab.text =@"地址";
        [tCell addSubview:_AddressField];
    }
    return tCell;
}
#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}


-(void) requestListData
{

    
    MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
    if ( tMainTabController.m_UserDic != nil) {
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        
        if ([_NameField.text length] <= 0) {
            [tAppDel showWithCustomView:@"请输入姓名" detailText:@"" isCue:-1 delayTime:2];
            return;
        }
        if ([_PhoneField.text length] <= 0) {
            [tAppDel showWithCustomView:@"请输入手机" detailText:@"" isCue:-1 delayTime:2];
            return;
        }
        if ([_AddressField.text length] <= 0) {
            [tAppDel showWithCustomView:@"请输入地址" detailText:@"" isCue:-1 delayTime:2];
            return;
        }
        [self addHudLoad];
        NSDictionary* tDataDic = [tMainTabController.m_UserDic objectForKey:@"data"];
        NSString* tURLStr = [NSString stringWithFormat:@"%@ac=book&class_ids=%@&cur_user_id=%@&name=%@&address=%@&mobile=%@",RequestCurrentURL,m_BaoIDs,[tDataDic objectForKey:@"user_id"],_NameField.text,_AddressField.text,_PhoneField.text];
        
        tURLStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)tURLStr, nil, nil, kCFStringEncodingUTF8);
        ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tURLStr]];
        [tRequestPage setDelegate:self];
        [tRequestPage setDidFailSelector:@selector(requestListFail:)];
        [tRequestPage setDidFinishSelector:@selector(requestListFinish:)];
        [tRequestPage startAsynchronous];
    }else{
        [_NavBtt removeFromSuperview];
        LoginViewController* tLogin = [[LoginViewController alloc] init];
        tLogin.pushtype = 0;
        tLogin.hidesBottomBarWhenPushed = YES;
        tLogin.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tLogin animated:YES];
        [tLogin release];
    }
    
}

-(void) requestListFail:(ASIHTTPRequest*)request
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestListFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            if ([[tRealDataDic objectForKey:@"result"] intValue] == 1) {
                BaoSusViewController* tBaoSusVC = [[BaoSusViewController alloc] init];
                tBaoSusVC.navigationItem.hidesBackButton =YES;
                [self.navigationController pushViewController:tBaoSusVC animated:YES];
                [tBaoSusVC release];
            }else{
                [tAppDel showWithCustomView:@"报名请求失败" detailText:@"" isCue:-1 delayTime:2];
            }
        }else{
            
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:NO delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}


#pragma mark -
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
@end
